import history from "@/utils/history";
import styles from "./index.module.scss";
import { Button, Modal, Upload, message } from "antd";
import ImgCrop from "antd-img-crop";
import { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import React, { useCallback, useEffect, useRef, useState } from "react";

import { SortAscendingOutlined } from "@ant-design/icons";

type Props = {
  fileData: any[];
  max: number;
  myUrl: string;
  fromData: any;
};

function ZupClipImg({ fileData, max, myUrl, fromData }: Props) {
  useEffect(() => {
    const arr: UploadFile[] = fileData.map((v) => ({
      uid: v.id,
      name: v.fileName,
      status: "done",
      percent: 100,
      url: "https://ytxbwg.4dage.com" + v.filePath,
      response: {
        data: v,
      },
    }));
    setFileList(arr);
  }, [fileData]);
  const [modal, contextHolder] = Modal.useModal();

  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const FileProps: UploadProps = {
    action: myUrl,
    headers: {
      token:
        "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlkIjoxLCJpc0FkbWluIjoxLCJ1c2VyTmFtZSI6ImFkbWluIiwiZXhwIjoxNjg5NjQ3NjY2LCJyb2xlS2V5cyI6WyJzeXNfYWRtaW4iXSwiaWF0IjoxNjg5NTYxMjY2LCJqdGkiOiI1ZmEyZGU5ZC04MDU0LTQyODUtYTEzNS1hMWFlNTk5MGYxZjEifQ.C5NjmMhybKHLdo1gJ6hPL9PJjaEOkLWdsVp_smOtHnQ",
    },
    listType: "picture-card",
    data: fromData,
    fileList,
    onChange(info) {
      setFileList([...info.fileList]);

      const { status } = info.file;
      if (status !== "uploading") {
        // 检查请求状态
        const response = info.file.response || {};

        if (response.code !== 0) {
          setFileList(info.fileList.filter((v) => v.uid !== info.file.uid));
        }
        if (response.code === 5001 || response.code === 5002) {
          message.warning("登录失效!");
          history.push("/login");
          return false;
        }

        // console.log(info.file, info.fileList);
      }
      if (status === "done") {
        // message.success(`${info.file.name} 上传成功.`);
      } else if (status === "error") {
        message.error(`${info.file.name} 上传失败.`);
        // 去掉列表中的失败状态文件
        setFileList(info.fileList.filter((v) => v.uid !== info.file.uid));
      }
    },
    // 点击删除
    async onRemove() {
      const promiseFu = new Promise((resolve: (value: boolean) => void) => {
        modal.confirm({
          title: "操作确认",
          content: "是否确认删除？",
          okText: "确定",
          cancelText: "取消",
          onOk() {
            resolve(true);
          },
          onCancel() {
            resolve(false);
          },
        });
      });
      return await promiseFu;
    },
    onPreview(info) {
      console.log("------点击了查看图片", info);
    },
    onDownload(info) {
      console.log("-------点击了下载", info);
    },
    showUploadList: {
      showDownloadIcon: true,
    },
  };

  // 文件上传之前
  const beforeCrop = useCallback((file: RcFile) => {
    if (file.name.includes("4dage")) {
      // console.log("校验不通过，不上传");
      message.error(`${file.name}不符合上传需求`);
      return Upload.LIST_IGNORE;
    } else return true;
  }, []);

  // 有关排序的操作：

  //  点击排序
  const sortShowFu = useCallback((ind: number) => {
    setSortClickNum(ind);
    setSortValue(ind + 1 + "");
    setTimeout(() => {
      if (showInpRef.current) showInpRef.current.focus();
    }, 100);
  }, []);

  const showInpRef = useRef<HTMLInputElement>(null);
  const [sortClickNum, setSortClickNum] = useState(-1);

  const [sortValue, setSortValue] = useState("");

  const sortValueChange = useCallback(
    (val: string) => {
      if (Number(val) > fileList.filter((v) => v.status === "done").length)
        val = fileList.filter((v) => v.status === "done").length + "";
      setSortValue(val.replace(/^(0+)|[^\d]+/g, ""));
    },
    [fileList]
  );

  // 点击序号的 √
  const sortOkFu = useCallback(
    (oldInd: number) => {
      if (!sortValue) return message.warning("请输入序号值!");

      const newInd = Number(sortValue) - 1;

      if (oldInd === newInd) return message.warning("不能和之前的序号一样!");

      const newArr = [...fileList];
      newArr[oldInd] = fileList[newInd];
      newArr[newInd] = fileList[oldInd];
      setFileList(newArr);

      message.success("修改序号成功!");
      setSortClickNum(-1);
    },
    [fileList, setFileList, sortValue]
  );

  const inputKeyFu = useCallback(
    (e: React.KeyboardEvent<HTMLInputElement>, ind: number) => {
      if (e.key === "Enter") {
        sortOkFu(ind);
        e.preventDefault();
      }
    },
    [sortOkFu]
  );

  return (
    <div className={styles.ZupClipImg}>
      <ImgCrop
        // 图片质量 默认0.4
        quality={1}
        rotationSlider //可以旋转
        beforeCrop={(info) => beforeCrop(info)}
        modalTitle="裁剪图片"
        aspect={1 / 1.3} //裁剪图片宽高比
        // fillColor='white' //当裁切图像小于画布时的填充颜色
        // showGrid={true} //显示九宫格
        // cropShape='rect' //rect:方形--round：圆形
      >
        <Upload {...FileProps}>
          {fileList.length <= max - 1 && "+ Upload"}
        </Upload>
      </ImgCrop>
      <br />

      {/* 排序修改功能 */}

      <div className="ZCsortBox">
        {fileList.map((v, i) => (
          <div
            className="ZCsortBoxRow"
            key={v.uid}
            title="文件排序"
            hidden={fileList.length <= 1}
          >
            <div onClick={() => sortShowFu(i)} hidden={v.status !== "done"}>
              <SortAscendingOutlined rev={undefined} />
              &nbsp; 序号:{i + 1}
            </div>
            {sortClickNum === i ? (
              <input
                className="ZCInput"
                onBlur={() => setSortClickNum(-1)}
                onKeyDown={(e) => inputKeyFu(e, i)}
                ref={showInpRef}
                maxLength={5}
                type="text"
                value={sortValue}
                onChange={(e) => sortValueChange(e.target.value)}
              />
            ) : null}
          </div>
        ))}
      </div>

      <div className="ZCTit">
        支持上传 jpg，png，jpeg 格式图片，最大上传5M
        <div hidden={fileList.length <= 1}>
          点击
          <SortAscendingOutlined rev={undefined} />
          ，输入 1 - {fileList.filter((v) => v.status === "done").length}{" "}
          的整数，按 Enter 键来交换2个文件的位置
        </div>
      </div>

      <Button onClick={() => console.log("点击确定", fileList)}>确定</Button>
      {contextHolder}
    </div>
  );
}

const MemoZupClipImg = React.memo(ZupClipImg);

export default MemoZupClipImg;
